<template>
  <div v-if="visible" class="dialog-overlay" @click="handleOverlayClick">
    <div class="dialog" @click.stop>
      <div class="dialog-header">
        <h2>加入房间</h2>
        <button class="close-btn" @click="$emit('close')">
          <span>&times;</span>
        </button>
      </div>
      
      <div class="dialog-content">
        <!-- 当传入 initialRoomId 或已输入 roomId 时：展示房间信息 + 加入按钮 -->
        <template v-if="roomInfo">
          <div class="info-card">
            <div class="info-row"><span>房间名</span><span>{{ roomInfo.roomName }}</span></div>
            <div class="info-row host-row">
              <span>房主</span>
              <span class="host-wrap">
                <span class="host-avatar">
                  <img v-if="hostAvatarUrl" :src="hostAvatarUrl" alt="host" />
                  <span v-else>{{ hostInitial }}</span>
                </span>
                <span class="host-name">{{ hostName || '未知' }}</span>
              </span>
            </div>
            <div class="info-row"><span>人数</span><span>{{ roomInfo.currentPlayers }} / {{ roomInfo.maxPlayers }}</span></div>
            <div class="info-row"><span>状态</span>
              <span class="status-chip" :class="statusClass">{{ statusText }}</span>
            </div>
          </div>
          <button 
            class="submit-btn" 
            @click="handleJoinRoom"
            :disabled="!form.roomId.trim() || isJoining || statusText==='游戏中'"
          >
            {{ isJoining ? '加入中...' : '加入房间' }}
          </button>
        </template>

        <!-- 否则：展示输入框 -->
        <div v-else class="form-container">
          <div class="form-group">
            <label for="roomId">房间ID</label>
            <input 
              id="roomId"
              v-model="form.roomId" 
              type="text" 
              placeholder="请输入房间ID"
              maxlength="36"
            />
          </div>
          <button 
            class="submit-btn" 
            @click="handleJoinRoom"
            :disabled="!form.roomId.trim() || isJoining"
          >
            {{ isJoining ? '加入中...' : '加入房间' }}
          </button>
        </div>
      </div>
      
      <!-- 错误信息显示 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useSocketStore } from '@/stores/socket'
import { useGameStore } from '@/stores/game'
import { useUserStore } from '@/stores/user'
import { useRoomStore } from '@/stores/room'
import { roomAPI } from '@/api'
import request from '@/utils/request.js'

export default {
  name: 'JoinRoomDialog',
  // 输入：可见性与是否启用模拟模式
  props: {
    visible: { type: Boolean, default: false },
    mock: { type: Boolean, default: true },
    initialRoomId: { type: String, default: '' }
  },
  // 输出：关闭与加入成功事件
  emits: ['close', 'room-joined'],
  setup(props, { emit }) {
    const socketStore = useSocketStore()
    const gameStore = useGameStore()
    
    const isJoining = ref(false)
    const errorMessage = ref('')
    const userStore = useUserStore()
    const roomStore = useRoomStore()
    
    // 表单数据
    const form = ref({ roomId: '' })
    const roomInfo = ref(null)
    
    // 表单验证
    const isFormValid = computed(() => form.value.roomId.trim())
    
    // 同步初始 roomId（打开时或 props 变化时）
    const syncInitialId = () => {
      if (props.initialRoomId && (!form.value.roomId || form.value.roomId.length < 6)) {
        form.value.roomId = props.initialRoomId
        loadRoomInfo()
      }
    }

    syncInitialId()
    watch(() => props.initialRoomId, () => syncInitialId())
    watch(() => props.visible, (v) => { if (v) syncInitialId() })

    const statusText = computed(() => {
      const s = (roomInfo.value?.status || '').toLowerCase()
      if (s === 'playing') return '游戏中'
      if (s === 'finished') return '已结束'
      return '等待中'
    })
    const statusClass = computed(() => ({ playing: statusText.value === '游戏中', finished: statusText.value === '已结束', waiting: statusText.value === '等待中' }))

    // 解析房主头像/名字
    const hostName = computed(() => {
      const creator = roomInfo.value?.creator || roomInfo.value?.owner || ''
      if (creator) return creator
      const p = (roomInfo.value?.players || [])[0]
      return p?.username || p?.name || p?.nickname || ''
    })

    const resolveAvatarUrl = (fileOrUrl) => {
      if (!fileOrUrl) return ''
      if (/^https?:\/\//i.test(fileOrUrl)) return fileOrUrl
      const base = (request?.defaults?.baseURL || '').replace(/\/+$/, '')
      return `${base}/users/avatar-file/${fileOrUrl}`
    }

    const hostAvatarUrl = computed(() => {
      const players = roomInfo.value?.players || []
      const creator = hostName.value
      let p = players.find(x => (x.username || x.name || x.nickname) === creator)
      if (!p && players.length > 0) p = players[0]
      return resolveAvatarUrl(p?.avatar || p?.avatarUrl || '')
    })

    const hostInitial = computed(() => (hostName.value || 'U').trim()[0]?.toUpperCase() || 'U')

    // 处理加入房间
    const handleJoinRoom = async () => {
      if (!isFormValid.value) return
      
      isJoining.value = true
      errorMessage.value = ''
      
      try {
        const roomData = { roomId: form.value.roomId.trim(), playerName: userStore.userDisplayName || userStore.user?.nickname || userStore.user?.username || '玩家' }
        
        if (props.mock) {
          // 模拟模式：直接返回成功，并随机给出一个房间名和时长
          setTimeout(() => {
            const fakeRoomName = `房间-${roomData.roomId}`
            const fakeGameTime = 120
            gameStore.currentPlayer = roomData.playerName
            gameStore.gameTime = fakeGameTime
            emit('room-joined', { roomId: roomData.roomId, roomName: fakeRoomName, playerName: roomData.playerName, roomData: { maxPlayers: 5 } })
            isJoining.value = false
          }, 600)
          return
        }
        
        // 先用 REST 加入，成功率更高
        try {
          await roomStore.joinRoom(roomData.roomId)
          emit('room-joined', { roomId: roomData.roomId, playerName: roomData.playerName })
          isJoining.value = false
          return
        } catch (restErr) {
          // REST 失败再尝试 SignalR 兜底
          const success = socketStore.joinRoom(roomData)
          if (success) {
            socketStore.once('RoomJoined', (data) => {
              if (data.success) {
                gameStore.currentPlayer = roomData.playerName
                // 只有在数据中明确提供游戏时间时才设置，避免覆盖正确的时间
                if (data.gameTime && typeof data.gameTime === 'number') {
                  gameStore.gameTime = data.gameTime
                }
                emit('room-joined', { roomId: roomData.roomId, playerName: roomData.playerName, roomData: data.roomData })
              } else {
                errorMessage.value = data.message || '加入房间失败'
              }
              isJoining.value = false
            })
            socketStore.once('RoomError', (data) => {
              errorMessage.value = data.message || '加入房间时发生错误'
              isJoining.value = false
            })
          } else {
            errorMessage.value = '加入房间失败，请稍后重试'
            isJoining.value = false
          }
        }
      } catch (error) {
        errorMessage.value = '加入房间失败：' + error.message
        isJoining.value = false
      }
    }
    
    // 处理遮罩层点击关闭
    const handleOverlayClick = () => { emit('close') }

    const loadRoomInfo = async () => {
      const rid = form.value.roomId?.trim()
      if (!rid) return
      try {
        const res = await roomAPI.getRoomInfo(rid)
        const data = res?.data || res
        roomInfo.value = data || null
      } catch (_) { roomInfo.value = null }
    }
    
    onMounted(() => { if (form.value.roomId) loadRoomInfo() })

    return { form, isJoining, errorMessage, isFormValid, handleJoinRoom, handleOverlayClick, roomInfo, statusText, statusClass, hostName, hostAvatarUrl, hostInitial }
  }
}
</script>

<style scoped>
.dialog-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.dialog { background: white; border-radius: 12px; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); width: 90%; max-width: 480px; max-height: 90vh; overflow-y: auto; }
.dialog-header { display: flex; justify-content: space-between; align-items: center; padding: 24px 24px 0 24px; border-bottom: 1px solid #e5e7eb; padding-bottom: 16px; }
.dialog-header h2 { margin: 0; font-size: 1.5rem; font-weight: 600; color: #111827; }
.close-btn { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 4px; border-radius: 4px; transition: color 0.2s; }
.close-btn:hover { color: #374151; }
.dialog-content { padding: 24px; }
.form-container { display: flex; flex-direction: column; gap: 20px; }
.form-group { display: flex; flex-direction: column; gap: 8px; }
.form-group label { font-weight: 500; color: #374151; font-size: 0.875rem; }
.form-group input { padding: 12px 16px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 1rem; transition: border-color 0.2s, box-shadow 0.2s; }
.form-group input:focus { outline: none; border-color: #10b981; box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1); }
.submit-btn { padding: 12px 24px; border: none; border-radius: 8px; font-size: 1rem; font-weight: 500; cursor: pointer; transition: all 0.2s; margin-top: 8px; background-color: #10b981; color: white; }
.submit-btn:hover:not(:disabled) { background-color: #059669; }
.submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.error-message { margin: 16px 24px 24px 24px; padding: 12px 16px; background-color: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; color: #dc2626; font-size: 0.875rem; }
.info-card { border: 1px solid #e5e7eb; background: #fafafa; border-radius: 12px; padding: 16px; margin-bottom: 12px; }
.info-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; color: #374151; }
.host-row .host-wrap { display: inline-flex; align-items: center; gap: 8px; }
.host-avatar { width: 28px; height: 28px; border-radius: 50%; background: #e5e7eb; display: inline-flex; align-items: center; justify-content: center; font-weight: 800; color: #111827; }
.host-avatar img { width: 100%; height: 100%; border-radius: 50%; display: block; }
.host-name { font-weight: 700; color: #111827; }
.status-chip { padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 700; }
.status-chip.waiting { background: #eef2ff; color: #3730a3; }
.status-chip.playing { background: #ecfdf5; color: #065f46; }
.status-chip.finished { background: #fee2e2; color: #991b1b; }
@media (max-width: 640px) { .dialog { width: 95%; margin: 20px; } .dialog-header, .dialog-content { padding: 16px; } }
</style> 